<?php

namespace plugin\laoha\app\admin\controller;

use plugin\laoha\app\model\Nav;
use support\Request;
use plugin\laoha\app\validate\TitleValidate;

class NavController extends CrudController
{
  protected $noNeedAuth = ['select', 'show', 'check', 'list'];
  protected $dataLimitField = false;
  protected $dataLimit = 'auth';
  protected $root = '';

  public function __construct()
  {
    $this->model = new Nav;
    $this->validate = new TitleValidate;
    $roots = plugin_config_merge('nav.roots');
    $root = request()->input('root', array_keys($roots)[0]);
    $this->root = $root;
  }

  public function index()
  {
    $root = $this->root;
    $roots = plugin_config_merge('nav.roots');
    $navs = [];
    foreach ($roots as $k => $v) {
      if ($root == $k) {
        $navs[] = ['label' => $v['title'], "to" => '/app/laoha/admin/nav?root=' . $k, "active" => true];
      } else {
        $navs[] = ['label' => $v['title'], "to" => '/app/laoha/admin/nav?root=' . $k];
      }
    }

    $root_name = $roots[$root]['title'];
    $rules = $this->getRules();
    return view('nav/index', ['params' => ['rules' => $rules, 'roots' => $roots, 'root' => $root, 'navs' => $navs, 'root_name' => $root_name]]);
  }

  /**
   * 列表
   * @param $request
   */
  public function list(Request $request)
  {
    $this->set = ['page_type' => 3, 'order_by' => 'parent_id,sort', 'root' => $this->root];
    return parent::list($request);
  }

  /**
   * 排序
   *
   * @Author 老蟹 7040867@qq.com    DateTime 2023-10-16
   * @param Request $request
   * @return void
   */
  public function order(Request $request)
  {
    $data = $request->input('rowsDiff');
    $data = $data[0];
    if ($id = $data['id']) {
      unset($data['id']);
      $this->model->where('id', $id)->update($data);
      return json_ok('操作完成');
    } else {
      return json_fail('未找到指定内容');
    }
  }

  /**
   * 查询
   * @param $request
   */
  public function select(Request $request)
  {
    $config = plugin_config_merge('nav.roots');
    $level = $config[$this->root]['level']??2;
    if($level<2) return json_ok([]);
    $builder = $this->builder ?: $this->model;
    $this->set = $this->limitData($this->set);
    $set = array_merge($request->all(), $this->set);
    $set['page_type'] = 3;
    $data = laoha_query($builder, $set);
    $data = $this->filter_select($data,$level);
    return json_ok($data);
  }

  protected function filter_select($data,$level=2){
    foreach($data as $k=>$d){
      if($d['level']+1===$level){
        unset($data[$k]['children']);
      }elseif(!empty($d['children'])){
        $data[$k]['children'] = $this->filter_select($d['children'],$level);
      }
    }
    return $data;
  }
}
